/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-11-12
 * Time:15:57
 */

/**
 * LCR 049. 求根节点到叶节点数字之和
 */

public class sumNumbers {
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        public int sumNumbers(TreeNode root) {
            return dfs(root,0);// 初始前项值为0
        }

        private int dfs(TreeNode root, int presum) {
            presum = presum * 10 + root.val;// 每到下一个节点都需要讲前项值 * 10 来加上当前节点的值
            if (root.left == null && root.right == null){
                return presum;// 当节点的左右节点都为空才返回
            }
            int ret = 0;
            if (root.left != null){
                ret += dfs(root.left,presum);
            }
            if (root.right != null){
                ret += dfs(root.right,presum);
            }
            return ret;
        }
    }
}
